package com.cuit.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.cuit.oss.service.OssService;
import com.cuit.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
        String bucketName=ConstantPropertiesUtils.BUCK_NAME;
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            //生成随机数
            String uuid=UUID.randomUUID().toString().replaceAll("-","");
            //把文件按照日期进行分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //获取文件名称
            String filename =datePath+"/"+uuid+file.getOriginalFilename();

            //调用oss方法实现上传
            ossClient.putObject(bucketName, filename, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();

            //把文件路径进行返回，手动拼接路径
            //https://hor1zon.oss-cn-chengdu.aliyuncs.com/Hor1zon.jpg
            String url="https://"+bucketName+"."+endpoint+"/"+filename;
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
